/*
创建时间：2024年4月2日（由CCD290_readout_faster.c修改而来）
目的：尝试缩短“读出时间”

*/

#include "SchmidtCAM.h"

/*double time_diff(struct timeval *start, struct timeval *end){*/
/*    return (end->tv_sec - start->tv_sec) + 1e-6*(end->tv_usec - start->tv_usec);*/
/*}*/

int main( int argc, char *argv[] ){

    struct timeval start;
	struct timeval end;
	
	gettimeofday(&start, NULL);

/**** handle option parameters ****/
	int opt;
	opterr = 1;

	uint32_t n_row 			= 4700;	// default
	uint32_t n_col 			= 1250;	// default
	uint32_t fast_read_opt	= 1;
	uint32_t n_bytes	    = 2;	// default 32bits float

	char fout_name[1024]= "tmp/tmp.bin";
	
	while( (opt=getopt(argc,argv,"r:c:f:o:b:")) != -1 ){
		switch(opt){
			case 'r':
				n_row = (uint32_t)atoi(optarg);
				printf("(%s)> Num. of vertical transfers: %d\n", __FUNCTION__, n_row);
				break;
			case 'c':
				n_col = (uint32_t)atoi(optarg);
				printf("(%s)> Num. of horizontal transfers: %d\n", __FUNCTION__, n_col);
				break;
			case 'f':
				fast_read_opt = (uint32_t)atoi(optarg);
				break;
			case 'o':
				sprintf(fout_name, "%s", optarg);
				printf("(%s)> data will be saved into: %s\n", __FUNCTION__, fout_name);
				break;
			case 'b':
				n_bytes = (uint32_t)atoi(optarg);
				printf("(%s)> date format %d bytes (2 bytes: 16bits unsigned; 4 bytes: 32bits float).\n", __FUNCTION__, n_bytes);
				break;
			default:
				break;
		}
	}
	
/*	exit(0);*/

/**** memery map ****/

	int fd_gpio = open("/dev/mem", O_RDWR | O_SYNC);

	// ADDR_GPIO_OUT --> 0x41220000
	uint32_t *gpio_reg_ctrl = mmap(NULL, 4, PROT_READ | PROT_WRITE, MAP_SHARED, fd_gpio, ADDR_GPIO_OUT);

	// ADDR_GPIO_IN  --> 0x41210000
	uint32_t *gpio_reg_status = mmap(NULL, 4, PROT_READ | PROT_WRITE, MAP_SHARED, fd_gpio, ADDR_GPIO_IN);

	// ADDR_PL_PS_DDR_CNT --> 0x41210008
	// uint32_t *gpio_reg_pl_ps_ddr_cnt = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd_gpio, ADDR_PL_PS_DDR_CNT);
	uint32_t *gpio_reg_pl_ps_ddr_cnt = gpio_reg_status + 2;

/**** call ccd_exposure ****/

	ccd_readout( gpio_reg_ctrl, 
                 gpio_reg_status, 
                 gpio_reg_pl_ps_ddr_cnt, 
                 n_row,
                 n_col,
				 n_bytes,
                 fast_read_opt,
                 fout_name );

	gettimeofday(&end, NULL);
    printf("**> Faster readout used time: %10.6f s\n", time_diff(&start, &end));
	
	munmap(gpio_reg_ctrl,10);
	munmap(gpio_reg_status,10);
/*	munmap(gpio_reg_pl_ps_ddr_cnt,10);*/
	close(fd_gpio);
	
/*	DropCaches(3);    //  清空缓存*/

	return 0;
}
